<template>

</template>

<script>
/**
 * 作弊码：检测到使用作弊码执行相关操作
 * 默认作弊码是：上上下下左右左右BA
 * 检测到作弊码执行的函数是success
 * eg：
 * <cheat-code :cheat-code="code" @success="success"/>
 *
 * import cheatCode from "@/views/components/key-listen/cheatCode";
 *
 * export default {
 *  components:{
 *    cheatCode,
 *  },
 *  data () {
 *    return {
 *      code:['1','2','1','2']
 *    }
 *  },
 *  methods:{
 *    success(keySeq) {
 *      console.log("link start ... %o",keySeq);
 *      this.$router.push("/index");
 *    },
 *  }
 * };
 */
export default {
  name: "konamiCode",
  props: {
    //字符串数组
    cheatCode:{
      require: false,
      type: Array,
      default: () => ['ArrowUp','ArrowUp','ArrowDown','ArrowDown','ArrowLeft','ArrowRight','ArrowLeft','ArrowRight','b','a'],//上上下下左右左右BA
    },
  },
  data() {
    return {
      // konamiCode:[38,38,40,40,37,39,37,39,66,65],//上上下下左右左右BA
      // konamiCode:['ArrowUp','ArrowUp','ArrowDown','ArrowDown','ArrowLeft','ArrowRight','ArrowLeft','ArrowRight','b','a'],//上上下下左右左右BA
      codeSeq: [],
    };
  },
  created () {
    this.keyDown()
  },
  beforeDestroy () {
    this.keyDownReview()
  },
  methods: {
    //按键恢复
    keyDownReview() {
      document.onkeydown = function (event) {
        var e = event || window.event;
        e.returnValue = true;
      }
    },
    //键盘按钮截获
    keyDown() {
      document.onkeydown = e => {
        if (this.codeSeq.length===this.cheatCode.length){
          this.codeSeq.shift();
        }
        this.codeSeq.push(e.key);
        if (this.arrayEqual(this.cheatCode, this.codeSeq)){
          this.success(this.codeSeq);
          this.codeSeq = [];
        }

      }
    },
    // 向父组件提供点击事件
    success() {
      this.$emit("success", this.codeSeq);
    },
    arrayEqual(arr1, arr2) {
      if (arr1.length !== arr2.length){
        return false;
      }
      for(let i = 0; i < arr1.length; i++){
        if (arr1[i] !== arr2[i]){
          return false;
        }
      }
      return true;
    }
  },
}
</script>

